﻿using System;
using System.Collections.Generic;
using System.Linq;
using Qask.Data.Core;

namespace Qask.Service.Core
{
    public class PostService : IPostService
    {
        private readonly IPostRepository _postRepository;

        public PostService(IPostRepository postRepository)
        {
            _postRepository = postRepository;
        }

        public List<PostViewModel> GetQuestions()
        {
            var specification = new Specification<Post>(m => m.PostTypeId == int.Parse(PostType.Question.ToString()));
            IEnumerable<Post> posts = _postRepository.GetPosts(specification);
            return CustomMapper.Map<Post, PostViewModel>(posts).ToList();
        }

        public List<PostViewModel> GetQuestions(PostFilterViewModel filterView)
        {
            var specification = new Specification<Post>(m => m.PostTypeId == (int)PostType.Question);
            IEnumerable<Post> posts = _postRepository.GetPosts(specification);
            return CustomMapper.Map<Post, PostViewModel>(posts).ToList();
        }

        public PostViewModel Get(int id)
        {
            var specification = new Specification<Post>(m => m.Id == id);
            Post post = _postRepository.GetPosts(specification).First();
            return CustomMapper.Map<Post, PostViewModel>(post);
        }

        public int CreateQuestion(CreateQuestionViewModel newQuestion, string userId)
        {
            Post question = new Post
            {
                CreationDate = DateTime.UtcNow,
                CreatedByUserId = userId,
                PostTypeId = (int) PostType.Question,
                Title = newQuestion.Title,
                Body = newQuestion.Body
            };

            Post createdQuestion = _postRepository.CreatePost(question);
            return createdQuestion.Id;
        }

        public PostViewModel UpdateQuestion(PostViewModel updatedPost, string userId)
        {
            Post post = CustomMapper.Map<PostViewModel, Post>(updatedPost);

            post.CreatedByUserId = userId;
            post = _postRepository.UpdatePost(post);

            return CustomMapper.Map<Post, PostViewModel>(post);
        }
    }
}
